#include <stdio.h> //f*(), printf(), perror()...
#include <sys/unistd.h> //getcwd(), get*id(), fork(), execlp()...
#include <sys/stat.h> //for the stat structure
#include <dirent.h> //defines d_type, opendir(), and so on
#include <time.h> //no warning when I don't include this, why?
#include <errno.h> //for the errno variable
#include <string.h> //for strerror

int main(int argc, char* argv[]) {
	if (fork()) {
		struct dirent *e;
		struct stat s;
		struct tm *lt;
		DIR *d = opendir(".");
		FILE *f = fopen("index.txt", "w");
		if (f) {
			while (e = readdir(d)) {
				if (*e->d_name == '.')
					continue; //ignored hidden files
				if (stat(e->d_name, &s) != 0)
					fprintf(stderr, "can't stat %s: %s\n",
						e->d_name, strerror(errno));
				else {
					lt = localtime(&s.st_mtime);
					fprintf(f, "inode %li, nlinks %3li, length %7li, "
						"date %2d/%2d/%d %2d:%2d:%2d, "
						"%s\n", 
						e->d_ino, s.st_nlink, s.st_size,
						lt->tm_mday, lt->tm_mon+1, 1900+lt->tm_year, //date
						lt->tm_hour, lt->tm_min, lt->tm_sec, //hour
						e->d_name); //name (no max len)
				}
			}
			closedir(d);
			fclose(f);
		}
		else {
			perror("open");
			return errno;
		}
		wait();
		return 0;
	}
	else {
		printf("Je suis le fils. uid=%d, gid=%d, pid=%5d, ppid=%5d\n", 
			getuid(), getgid(), getpid(), getppid());
		if (execlp("/bin/ps", "ps", "-lj", NULL) == -1) {
			perror("execlp");
			return errno;
		}
		else
			return 0;
	}
}